package cn.wolfcode.shop.web.advice;

import cn.wolfcode.shop.common.BusinessException;
import cn.wolfcode.shop.common.CommonExceptionAdvice;
import cn.wolfcode.shop.common.Result;
import cn.wolfcode.shop.msg.MemberServerCodeMsg;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 *  员工服务异常处理
 */
@ControllerAdvice
public class MemberServerControllerAdvice extends CommonExceptionAdvice {

    public MemberServerControllerAdvice() {
        //调用父类构造器，将原来的默认错误覆盖成我们想要的了
        super(MemberServerCodeMsg.USER_PARAM_ERROR);
    }

    /**
     * 处理用户参数校验之后的异常BindException
     * @param ex
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result handleParamEx(BindException ex){
        //出现的所有的错误
        List<ObjectError> allErrors = ex.getAllErrors();
        //获取第一个异常的信息提示给用户即可
        String defaultMessage = allErrors.get(0).getDefaultMessage();
        //调用MemberServerCodeMsg中定义的方法，将错误信息填进占位符当中去，再封装后返回
        return Result.error(MemberServerCodeMsg.USER_PARAM_ERROR.failParam(defaultMessage));
    }



    /**
     * 处理默认的错误
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleDefault(Exception ex){
        ex.printStackTrace();
        return Result.error(MemberServerCodeMsg.DEFAULT_ERROR);
    }
}
